package cn.edu.buaa.cnsatm.traffic_big_data_server.waterway.service;

import cn.edu.buaa.cnsatm.traffic_big_data_server.integrated.model.RoadStatusModel;
import cn.edu.buaa.cnsatm.traffic_big_data_server.integrated.dao.RoadStatusDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.DateUtil;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.JDBCUtil;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.WebSpiderUtil;
import cn.edu.buaa.cnsatm.traffic_big_data_server.waterway.dao.OceanDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.waterway.dao.TyphoonDAO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;

public class TyphoonService {

    public static String typhoonForecastAndProhibitNavigation(int top_num) throws SQLException {
        /**
         * @author: TW创建，LX修改
         * @methodName: typhoonForecastAndProhibitNavigation
         * @description: 获取最新的top_num个台风禁航警告
         **/
        /*台风http://www.wztf121.com/data/complex/201922.json*/
        ResultSet resultSet = TyphoonDAO.getTopKSeaBlockByTyphoon(top_num);
        JsonArray ja = new JsonArray();
        while (resultSet.next()){
            JsonObject jo = new JsonObject();
            jo.addProperty("info",resultSet.getString("block_description"));
            jo.addProperty("type", "台风");
            String datetime = resultSet.getString("block_start_time");
            jo.addProperty("datetime",datetime.substring(0, datetime.length() - 3));
            ja.add(jo);
        }
        resultSet.getStatement().close();
        resultSet.close();
        return ja.toString();
    }

    public static String getTyphoonFromWebAndSaveToDatabase(){
        /**
         * @author: LX
         * @methodName: getTyphoonFromWebAndSaveToDatabase
         * @description: 爬取台风实时数据，根据台风所在海域，给出禁航警告
         * @data:
         **/
        String typhoonSQLString = new String("-- 台风禁航数据\n");
        final String TYPHOON_URL_LEFT = "http://www.wztf121.com/data/complex/";
        final String TYPHOON_URL_RIGHT = ".json";
        String year = DateUtil.getCurrentTime().substring(0, 4);
        for(int i = 1; i < 100; i++){//遍历今年所有台风
            String typhoonNum = null;
            if (i < 10) typhoonNum = "0";
            typhoonNum = typhoonNum + String.valueOf(i);
            String typhoonURL = TYPHOON_URL_LEFT + year + typhoonNum + TYPHOON_URL_RIGHT;
            System.out.println(WebSpiderUtil.getJsonFromURL(typhoonURL));
            JSONArray typhoonJson = JSON.parseArray(WebSpiderUtil.getJsonFromURL(typhoonURL));
            String typhoonName = null;
            try{
                typhoonName = typhoonJson.getJSONObject(0).getString("name");
            }catch(Exception e){
                break;
            }
            //System.out.println(typhoonName);
            JSONArray typhoonJsonPoint = typhoonJson.getJSONObject(0).getJSONArray("points");
            //System.out.println(typhoonJsonPoint.toString());
            HashMap<String, Boolean> isOceanVisit = new HashMap<>();
            for(int j = 0; j < typhoonJsonPoint.size(); j++){//遍历台风经过的点
                Double longitude = typhoonJsonPoint.getJSONObject(j).getDouble("longitude");
                Double latitude  = typhoonJsonPoint.getJSONObject(j).getDouble("latitude");
                ResultSet ocean = OceanDAO.getOceanByLonAndLa(longitude, latitude);//获取台风所在海域
                try{
                    ocean.next();
                    String typhoonOcean = ocean.getString("name");//TODO:改字段名
                    if(!isOceanVisit.containsKey(typhoonOcean)){//台风在一个海域只警告一次
                        isOceanVisit.put(typhoonOcean, true);
                        if(60*60*24*5>DateUtil.getDateStringDifference(DateUtil.getCurrentTime(), typhoonJsonPoint.getJSONObject(j).getString("time").replace("T"," "))){
                            continue;
                        }
                        RoadStatusModel typhoonStatus = new RoadStatusModel("水路", "气象",
                                "受台风\"" + typhoonName + "\"影响，" + typhoonOcean + "区域禁航",
                                "st_makepoint(" + longitude + "," + latitude + ")",
                                typhoonJsonPoint.getJSONObject(j).getString("time").replace("T"," "), null, null,
                                typhoonJsonPoint.getJSONObject(j).getString("time").replace("T"," "));
                        typhoonStatus.setBlock_title(typhoonOcean + "区域受台风影响");
                        typhoonSQLString = typhoonSQLString + RoadStatusDAO.insertRoadStatus(typhoonStatus,false) + "\n";
                    }
                }catch (Exception e){ continue; }
            }
        }
        return typhoonSQLString;
    }
    public static void main(String args[]) throws IOException, SQLException {
        JDBCUtil.startConnection();
        System.out.println(typhoonForecastAndProhibitNavigation(5));
    }
}
